//
//  VRWebViewController.m
//  Rebate
//
//  Created by veer on 2017/7/1.
//  Copyright © 2017年 liuye. All rights reserved.
//

#import "VRWebViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <JavaScriptCore/JavaScriptCore.h>
#import <AddressBook/AddressBook.h>
#import "VRAddressBookTool.h"
#import "VRAlertView.h"
#import "VRUserInfo.h"
#import <CoreTelephony/CTCellularData.h>
#import "VRAuthenticationViewController.h"
#import "XScanViewController.h"

#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "UIImage+VR.h"

#import "FCPPSDK.h"

#import "shujumohePB.h"


@interface VRWebViewController () <UIWebViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIActionSheetDelegate, VRAuthenticationViewControllerDelegate, XScanViewControllerDelegate, WebViewJSExport, shujumoheDelegate> //

@property (nonatomic, weak) UIWebView *webView;

/** 假启动图 */
@property (nonatomic, weak) UIImageView *launchImgView;
/** 假启动图 */
@property (nonatomic, strong) VRAlertView *alertView;

@property (nonatomic, weak) UILabel *titleLbl;

@property(nonatomic,strong)JSContext *jsContext;
//防止多次定位
@property(nonatomic,assign)BOOL isFirstLocation;
@property (nonatomic, strong) CLLocationManager* locationManager;

// 关于定位
@property (nonatomic, strong) CLLocationManager *clMgr;
@property (nonatomic, strong) CLGeocoder *geo;
@property (nonatomic, strong) CLPlacemark *placemark;

@property (nonatomic, copy) NSString *typeStr;
@property (nonatomic, copy) NSString *userid;

// 正面图片
@property (nonatomic, strong) UIImage *frontImage;
@property (nonatomic, assign) BOOL frontImgCorrectness;
@property (nonatomic, strong) NSDictionary *frontDict;
// 反面图片
@property (nonatomic, strong) UIImage *identityImage;
@property (nonatomic, assign) BOOL identityImgCorrectness;
@property (nonatomic, strong) NSDictionary *identityDict;
// 人脸图片
@property (nonatomic, strong) UIImage *faceImage;
@property (nonatomic, assign) BOOL faceImgCorrectness;
@property (nonatomic, strong) NSDictionary *faceDict;
@property (nonatomic, strong) NSDictionary *compareDict;

@property (nonatomic, strong) NSDictionary *taobaoCertificationDict;
@property (nonatomic, copy) NSString *taskID;
@property (nonatomic, assign) NSInteger taobaoCertificationCount;

@end

@implementation VRWebViewController

static NSString * const reuseIdentifier = @"Cell";


- (instancetype)init
{
    if (self = [super init]) {
        self.isHaveNav = NO;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];

    // 设置useragent
//    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:[self newUser_Agent], @"UserAgent", nil];
//    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
    
    [self setupSubView];
    if (self.isHaveNav == YES) {
        [self setupNavxxxxxxxxxxxx];
        self.webView.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        self.webView.y = NAVIGATION_BAR_HEIGHT;
        self.webView.height = kScreenHeight - NAVIGATION_BAR_HEIGHT;
    }
    
    [self setCurcookies];
    
    if (!self.isHomeUrl) {
        
        [self loadUrlWith:self.urlStr];
    }else{
        
        [self.clMgr startUpdatingLocation];
        [self loadUrlWith:self.urlStr];
//        [self requestNetworkPermission];
    }
    
//    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//    btn.backgroundColor = [UIColor yellowColor];
//    [btn setTitle:@"text" forState:UIControlStateNormal];
//    btn.frame = CGRectMake(0, kScreenHeight - 100, 100, 30);
//    [btn addTarget:self action:@selector(onBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:btn];
}

- (void)setupNavxxxxxxxxxxxx
{
    
    UIView *navBarView = [[UIView alloc] init];
    navBarView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:navBarView];
    [navBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(NAVIGATION_BAR_HEIGHT);
    }];
    
    // 保存
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
    [backBtn addTarget:self action:@selector(onBackBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImage:[UIImage imageNamed:@"toolbar_navigation_icon_normal"] forState:UIControlStateNormal];
    backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    backBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, -10);
    [navBarView addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.centerY.mas_equalTo(navBarView.mas_bottom).offset(-22);
        make.width.mas_equalTo(30);
        make.height.mas_equalTo(20);
    }];
    
    // 标题
    UILabel *titleLbl = [[UILabel alloc] init];
    titleLbl.text = @"";
    titleLbl.font = VRFont(15);
    titleLbl.textColor = [UIColor blackColor];
    titleLbl.textAlignment = NSTextAlignmentCenter;
    [navBarView addSubview:titleLbl];
    self.titleLbl = titleLbl;
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(navBarView);
        make.centerY.mas_equalTo(navBarView.mas_bottom).offset(-22);
    }];
}

- (void)setupSubView
{
    
    UIWebView *webView = [[UIWebView alloc] init];
    webView.delegate = self;
    webView.frame = self.view.bounds;
    if (@available(iOS 11.0, *)) {
        
    }else{
        webView.scrollView.contentInset = UIEdgeInsetsMake(STATUS_BAR_HEIGHT, 0, 0, 0);
    }
    [self.view addSubview:webView];
    self.webView = webView;
    
    UIView *statusBarView = [[UIView alloc] init];
    statusBarView.backgroundColor = MAINColor;
    [self.view addSubview:statusBarView];
    [statusBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(STATUS_BAR_HEIGHT);
    }];
    
    // 遮罩
    UIImageView *launchImgView = [[UIImageView alloc] init];
    if (self.urlStr.length > 0 && self.isHomeUrl) {
        
        launchImgView.hidden = YES;
    }else{
        launchImgView.hidden = NO;
    }
    launchImgView.hidden = YES;
    launchImgView.image = [UIImage imageNamed:@"launch"];
    [self.view addSubview:launchImgView];
    self.launchImgView = launchImgView;
    [launchImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
}




- (void)loadUrlWith:(NSString *)urlStr
{
    [self jugeNewtWorkPermission2];
//    NSString *path =  [[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"];
//    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL fileURLWithPath:path]];
    
//    NSURLCache *cache = [NSURLCache sharedURLCache];
//    cache.
    
    NSLog(@"url:%@", urlStr);
    
//    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlStr] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
    
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlStr]];
    [self.webView loadRequest:request];
}


- (void)jugeNewtWorkPermission2
{
    switch ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus) {
        case AFNetworkReachabilityStatusReachableViaWWAN:
        {
            NSLog(@"------NetworkReachability2-----:AFNetworkReachabilityStatusReachableViaWWAN");
        }
        case AFNetworkReachabilityStatusReachableViaWiFi:
        {
            NSLog(@"------NetworkReachability2-----:AFNetworkReachabilityStatusReachableViaWiFi");
        }
            break;
        case AFNetworkReachabilityStatusNotReachable:
        {
            NSLog(@"------NetworkReachability2-----:AFNetworkReachabilityStatusNotReachable");
            [SVProgressHUD showErrorWithStatus:@"请检查网络"];
        }
            break;
        case AFNetworkReachabilityStatusUnknown:
        {
            NSLog(@"------NetworkReachability2-----:AFNetworkReachabilityStatusUnknown");
            [SVProgressHUD showErrorWithStatus:@"请检查网络"];
        }
            break;
        default:
            break;
    }
}


- (void)jugeNetworkPermission
{
    NSString *version = [UIDevice currentDevice].systemVersion;
    if (version.doubleValue >= 9.0) {
        
        // 针对 9.0 以上的iOS系统进行处理
        CTCellularData *cellularData = [[CTCellularData alloc]init];
        
        CTCellularDataRestrictedState state = cellularData.restrictedState;
        switch (state) {
            case kCTCellularDataRestricted:{
                    NSLog(@"----11111----Restricrted-------------");
                    self.launchImgView.hidden = YES;
                    self.launchImgView.hidden = NO;
                    self.alertView = [[VRAlertView alloc] initWithTitle:@"提示" message:@"无线数据服务未开启，请进入系统［设置］> [隐私] > [通讯录]中打开开关" sureBtn:@"去设置" cancleBtn:nil];
                    self.alertView.isHidenAlertBySure = NO;
                    self.alertView.resultIndex = ^(NSInteger index){
                        
                        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                        
                        if([[UIApplication sharedApplication] canOpenURL:url]) {
                            
                            NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
                            [[UIApplication sharedApplication] openURL:url];
                        }
                    };
                    [self.alertView showXLAlertView];
                }
                break;
            case kCTCellularDataNotRestricted:{
                    NSLog(@"----11111----Not Restricted");
                    self.launchImgView.hidden = YES;
                }
                break;
            case kCTCellularDataRestrictedStateUnknown:{
                    NSLog(@"----11111----Unknown");
                    self.launchImgView.hidden = NO;
                    [self requestNetworkPermission];
                }
                break;
            default:
                break;
        }
        
        
    } else {
        // 针对 9.0 以下的iOS系统进行处理
    }
    
}


- (void)requestNetworkPermission
{
    __weak typeof(self) weakSelf = self;
    CTCellularData *cellularData = [[CTCellularData alloc]init];
    cellularData.cellularDataRestrictionDidUpdateNotifier =  ^(CTCellularDataRestrictedState state){
        //状态改变时进行相关操作
        switch (state) {
            case kCTCellularDataRestricted:
            {
                NSLog(@"----222----Restricrted");
                dispatch_async(dispatch_get_main_queue(), ^{
//                    weakSelf.launchImgView.hidden = NO;
//                    weakSelf.alertView = [[VRAlertView alloc] initWithTitle:@"提示" message:@"无线数据服务未开启，请进入系统［设置］> [隐私] > [通讯录]中打开开关" sureBtn:@"去设置" cancleBtn:nil];
//                    weakSelf.alertView.isHidenAlertBySure = NO;
//                    weakSelf.alertView.resultIndex = ^(NSInteger index){
//
//                        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
//
//                        if([[UIApplication sharedApplication] canOpenURL:url]) {
//
//                            NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
//                            [[UIApplication sharedApplication] openURL:url];
//                        }
//                    };
//                    [weakSelf.alertView showXLAlertView];
                });
                
            }
                break;
            case kCTCellularDataNotRestricted:{
                
                NSLog(@"----222----Not Restricted");
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.webView reload];
//                    weakSelf.alertView.hidden = YES;
//                    weakSelf.launchImgView.hidden = YES;
                });
            }
                break;
            case kCTCellularDataRestrictedStateUnknown:{
                NSLog(@"----222----Unknown");
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    weakSelf.launchImgView.hidden = NO;
//                });
            }
                break;
            default:
                break;
        };
    };
}


- (void)requestContactPermission
{
    // 判断是否授权
    __weak typeof(self) weakSelf = self;
    ABAuthorizationStatus authorizationStatus = ABAddressBookGetAuthorizationStatus();
    if (authorizationStatus == kABAuthorizationStatusNotDetermined) {
        // 请求授权
        ABAddressBookRef addressBookRef = ABAddressBookCreate();
        ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
            if (granted) { // 授权成功
                
                NSLog(@"授权成功！");
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    weakSelf.launchImgView.hidden = YES;
                });
            } else {  // 授权失败
                
                NSLog(@"授权失败！");
                dispatch_async(dispatch_get_main_queue(), ^{
                    weakSelf.alertView = [[VRAlertView alloc] initWithTitle:@"提示" message:@"通讯录服务未开启，请进入系统［设置］> [隐私] > [通讯录]中打开开关" sureBtn:@"去设置" cancleBtn:nil];
                    weakSelf.alertView.isHidenAlertBySure = NO;
                    weakSelf.alertView.resultIndex = ^(NSInteger index){
                        
                        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                        
                        if([[UIApplication sharedApplication] canOpenURL:url]) {
                            
                            NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
                            [[UIApplication sharedApplication] openURL:url];
                            
                        }
                    };
                    [weakSelf.alertView showXLAlertView];
                });
            }
        });
    }else if (authorizationStatus == kABAuthorizationStatusDenied || authorizationStatus == kABAuthorizationStatusRestricted){
        
        NSLog(@"关闭授权！");
        //        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"您必须授权通讯录权限才能访问此APP" delegate:self cancelButtonTitle:nil otherButtonTitles:@"去设置", nil];
        //        [alert show];
        
        self.alertView = [[VRAlertView alloc] initWithTitle:@"提示" message:@"通讯录服务未开启，请进入系统［设置］> [隐私] > [通讯录]中打开开关" sureBtn:@"去设置" cancleBtn:nil];
        self.alertView.isHidenAlertBySure = NO;
        self.alertView.resultIndex = ^(NSInteger index){
            
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            
            if([[UIApplication sharedApplication] canOpenURL:url]) {
                
                NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
                [[UIApplication sharedApplication] openURL:url];
                
            }
        };
        [self.alertView showXLAlertView];
    }else{
        
        self.launchImgView.hidden = YES;
    }
    
    
}


- (void)takePhotoFromCamera
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        [imagePicker.navigationBar setBackgroundImage:[UIImage imageWithColor:RGBA(255, 255, 255, 0.95)] forBarPosition:UIBarPositionTopAttached barMetrics:UIBarMetricsDefault];
//        [imagePicker.navigationBar setBackgroundImage:[UIImage imageWithColor:[NAVColor]] forBarPosition:UIBarPositionTopAttached barMetrics:UIBarMetricsDefault];
        
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
        imagePicker.allowsEditing = YES;
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
        [self presentViewController:imagePicker animated:YES completion:nil];
    }
}

- (void)takePhotoFromPhotoLibrary
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        
        UIImagePickerController *imagePicker = [UIImagePickerController new];
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
//        imagePicker.navigationBar.backgroundColor = [UIColor whiteColor];
        [imagePicker.navigationBar setBackgroundImage:[UIImage imageWithColor:RGBA(255, 255, 255, 0.95)] forBarPosition:UIBarPositionTopAttached barMetrics:UIBarMetricsDefault];
        //        NSDictionary *dic = [XCommonMethod X_ReadJsonFileWithNFileName:[TXSakuraManager getSakuraCurrentName]];
//        [imagePicker.navigationBar setBackgroundImage:[UIImage imageWithColor:NAVColor] forBarPosition:UIBarPositionTopAttached barMetrics:UIBarMetricsDefault];
        
        imagePicker.allowsEditing = YES;
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
        imagePicker.navigationBar.barTintColor = [UIColor colorWithRed:20.f/255.0 green:24.0/255.0 blue:38.0/255.0 alpha:1];
        [self presentViewController:imagePicker animated:YES completion:nil];
    }
}


- (void)createJSBridge
{
    JSContext *jsContext = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.jsContext = jsContext;
//    JSValue *value = [JSValue valueWithNewObjectInContext:jsContext];
//    self.jsContext[@"js"] = self;
    //传定位信息
    WeakSelf(weakSelf)
    jsContext[@"upLoadAddressBook"] = ^(NSString *card){

        NSLog(@"------------upLoadAddressBook card:%@", card);
        dispatch_async(dispatch_get_main_queue(), ^{

            [weakSelf uploadContactsWithCard:card];
        });
    };

    jsContext[@"onUploadLocation"] = ^(NSString *card){

        NSLog(@"------------onUploadLocation card:%@", card);
        dispatch_async(dispatch_get_main_queue(), ^{

            [weakSelf uploadLocationWithCard:card];
        });
    };


    jsContext[@"onGetPicReq"] = ^(NSString *type, NSString *userid) {

        weakSelf.typeStr = type;
        weakSelf.userid = userid;
        dispatch_async(dispatch_get_main_queue(), ^{

            [weakSelf takePhotoFromCamera];
        });
    };

    // 身份证认证
    jsContext[@"upLoadSfsb"] = ^(NSString *userid) {

        weakSelf.userid = userid;
        NSLog(@"------------upLoadSfsb card:%@", userid);
        dispatch_async(dispatch_get_main_queue(), ^{

            VRAuthenticationViewController *authVc = [[VRAuthenticationViewController alloc] init];
            authVc.userid = userid;
            authVc.delegate = weakSelf;
            authVc.sfsbJk = weakSelf.sfsbJk;
            authVc.sfzsbd = weakSelf.sfzsbd;
            [weakSelf presentViewController:authVc animated:NO completion:nil];
        });
    };

    // 身份证认证
    jsContext[@"onScanClick"] = ^() {

        dispatch_async(dispatch_get_main_queue(), ^{

            XScanViewController *authVc = [[XScanViewController alloc] init];
            authVc.delegate = weakSelf;
            [weakSelf presentViewController:authVc animated:NO completion:nil];
        });
    };
    
    // 身份证认证
    jsContext[@"upLoadTbrz"] = ^(NSString *userid) {
        
        weakSelf.userid = userid;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [weakSelf taobaoCertification];
        });
    };

    jsContext.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
        context.exception = exceptionValue;
        //比如把js中的方法名改掉，OC找不到相应方法，这里就会打印异常信息
        NSLog(@"异常信息：%@", exceptionValue);
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"异常信息：%@", exceptionValue]];
    };

//    jsContext[@"js"] = value;
}

/** type: 1正面 2反面 3人脸识别 */
- (void)onGetPicReq:(NSString *)type
{
    NSLog(@"type:%@", type);
    
    self.typeStr = type;
    dispatch_async(dispatch_get_main_queue(), ^{
        
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从手机相册选择", nil];
        sheet.tag = 100;
        [sheet showInView:self.view];
    });
}


- (void)reload
{
    [self.webView reload];
}

#pragma mark - HTTPS证书信任,此方法必须放到conroller内。
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler
{
    NSURLProtectionSpace *protectionSpace = challenge.protectionSpace;
    if ([protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        SecTrustRef serverTrust = protectionSpace.serverTrust;
        completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:serverTrust]);
    } else {
        completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
    }
}


/**
 淘宝认证
 */
- (void)taobaoCertification
{
    PBBaseReq *br = [PBBaseReq new];
    br.partnerCode = kPartner_code;//合作方code
    br.partnerKey = kPartner_key;//合作方key
    br.channel_code = @"005003";//授权渠道code
    /*
     基础设置
     如果不用自定义PBBaseSet，withBaseSet传nil
     如果只用某一个颜色、字体大小、图片，创建PBBaseSet对象，给相应颜色、字体大小、图片的对象即可.
     */
    PBBaseSet *set = [PBBaseSet new];
    //导航栏颜色
    set.navBGColor = MAINColor;
    //导航栏标题颜色
    set.navTitleColor = [UIColor blackColor];
    //导航栏标题字体
    set.navTitleFont = [UIFont systemFontOfSize:15];
    //导航栏按钮图片
    set.backBtnImage = [UIImage imageNamed:@"toolbar_navigation_icon_normal"];
    
    [shujumohePB openPBPluginAtViewController:self withDelegate:self withReq:br withBaseSet:set];
}


- (void)thePBMissionWithCode:(NSString *)code withMessage:(NSString *)message
{
    /*
     code = 0:表示成功，其他状态请参考文档。
     */
    NSLog(@"状态码：%@    对应信息：%@",code,message);
    if (code.integerValue == 0) {
        
        self.taskID = message;
        [self getTaobaoCertificationInfoWith:message];
    }else{
        [SVProgressHUD showErrorWithStatus:@"认证错误，请重试"];;
    }
}


#pragma mark - JSExport
- (void)upLoadAddressBook:(NSString *)card
{
    NSLog(@"card:%@", card);
    //    [self uploadContactsWithCard:card];
}

- (void)onUploadLocation:(NSString *)card
{
    NSLog(@"card:%@", card);
    //    [self uploadLocationWithCard:card];
}

- (void)upLoadSfsb:(NSString *)userid
{
    NSLog(@"upLoadSfsb:%@", userid);
    //    [self uploadLocationWithCard:card];
}


#pragma mark - net
/** 上传联系人 */
- (void)uploadContactsWithCard:(NSString *)card
{
    // hud
    [SVProgressHUD setDefaultMaskType:(SVProgressHUDMaskTypeCustom)];
    [SVProgressHUD showWithStatus:@"上传数据中..."];
    
    NSMutableArray *contactDicts = [VRAddressBookTool getContactsWithBlock:nil];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    //    NSDictionary *dict = @{@"datas":@"123"};
    NSArray *array = @[@{@"name" : @"panxx1", @"number" : @""},
                       @{@"name" : @"", @"number" : @"18257149139"},
                       @{@"name" : @"panxx3", @"number" : @"18257149139"},
                       @{@"name" : @"panxx4", @"number" : @"18257149139"},
                       @{@"name" : @"panxx5", @"number" : @"18257149139"}];
    //    param[@"datas"] = @"[{\"name\":\"panxx\", \"phone\":\"18257149139\"}]";
    NSString *jsonStr = [self convertToJsonData:contactDicts];
    param[@"card"] = card;
    param[@"datas"] = jsonStr;
    
    NSLog(@"param:%@", param);
    
    AFHTTPSessionManager *sessionMgr = [AFHTTPSessionManager manager];
    
    sessionMgr.responseSerializer.acceptableContentTypes = [[NSSet  alloc] initWithObjects:@"application/json", nil];
    
    AFJSONResponseSerializer *json =[AFJSONResponseSerializer serializer];
    json.removesKeysWithNullValues = YES;
    sessionMgr.responseSerializer = json;
    
    sessionMgr.requestSerializer=[AFHTTPRequestSerializer serializer];
    
    // 设置超时时长
    [sessionMgr.requestSerializer willChangeValueForKey:@"timeoutInterval"];
//    sessionMgr.requestSerializer.timeoutInterval = 20.0;
    [sessionMgr.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    __weak typeof(self) weakSelf = self;
    [sessionMgr POST:self.txljk parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // hud
        [SVProgressHUD dismiss];
        NSLog(@"responseObject:%@", responseObject);
        
        NSInteger struts = [responseObject[@"struts"] integerValue];
        if (struts == 3){
            
            [SVProgressHUD showSuccessWithStatus:@"上传成功"];
            [weakSelf loadUrlWith:weakSelf.txlfhUrl];
        }else{
            
            [SVProgressHUD showErrorWithStatus:@"上传失败"];
            [weakSelf loadUrlWith:weakSelf.txlfhUrl];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"error:%@", error);
        [SVProgressHUD dismiss];
        if (error.code == -1009) {  // 网络连接错误
            
            [SVProgressHUD showErrorWithStatus:@"网络连接错误"];
        }else if (error.code == -1001){ // 链接超时
            
            [SVProgressHUD showErrorWithStatus:@"请求超时"];
        }else{
            
            [SVProgressHUD showErrorWithStatus:@"请求错误"];
        }
        [weakSelf loadUrlWith:weakSelf.txlfhUrl];
    }];
    
    [sessionMgr.operationQueue cancelAllOperations];
}

/** 上传联系人 */
- (void)uploadLocationWithCard:(NSString *)card
{
    // hud
    [SVProgressHUD showWithStatus:@"上传数据中..."];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"card"] = card;
    param[@"lng"] = [NSString stringWithFormat:@"%.3lf", [VRUserInfo shareUserInfo].longitude];
    param[@"lat"] = [NSString stringWithFormat:@"%.3lf", [VRUserInfo shareUserInfo].latitude];
    
    NSLog(@"param:%@", param);
    
    AFHTTPSessionManager *sessionMgr = [AFHTTPSessionManager manager];
    
    sessionMgr.responseSerializer.acceptableContentTypes = [[NSSet  alloc] initWithObjects:@"application/json", nil];
//    sessionMgr.responseSerializer.acceptableContentTypes = [[NSSet  alloc] initWithObjects:@"text/html", nil];
    
    AFJSONResponseSerializer *json =[AFJSONResponseSerializer serializer];
    json.removesKeysWithNullValues = YES;
    sessionMgr.responseSerializer = json;
    
    sessionMgr.requestSerializer=[AFHTTPRequestSerializer serializer];
    
    // 设置超时时长
    [sessionMgr.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    sessionMgr.requestSerializer.timeoutInterval = 30.0;
    [sessionMgr.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    __weak typeof(self) weakSelf = self;//API_upLoadLocation
    [sessionMgr POST:self.dlwJk parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // hud
        [SVProgressHUD dismiss];
        NSLog(@"responseObject:%@", responseObject);
        
        NSInteger struts = [responseObject[@"code"] integerValue];
        if (struts == 0){
            
            [SVProgressHUD showSuccessWithStatus:@"上传成功"];
            [weakSelf loadUrlWith:weakSelf.dlwzfhUrl];
        }else{
            
            [SVProgressHUD showErrorWithStatus:@"上传失败"];
            [weakSelf loadUrlWith:weakSelf.dlwzfhUrl];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"error:%@", error);
        [SVProgressHUD dismiss];
        if (error.code == -1009) {  // 网络连接错误
            
            [SVProgressHUD showErrorWithStatus:@"网络连接错误"];
        }else if (error.code == -1001){ // 链接超时
            
            [SVProgressHUD showErrorWithStatus:@"请求超时"];
        }else{
            
            [SVProgressHUD showErrorWithStatus:@"请求错误"];
        }
        [weakSelf loadUrlWith:weakSelf.dlwzfhUrl];
    }];
    
    [sessionMgr.operationQueue cancelAllOperations];
}


/** 上传联系人 */
- (void)uploadImageWithCard:(NSString *)card base64:(NSString *)base64
{
    // hud
    [SVProgressHUD showWithStatus:@"上传数据中..."];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"zplx"] = self.typeStr;
    param[@"userid"] = self.userid;
    param[@"imgwj"] = base64;
    
    NSLog(@"param:%@", param);
    
    AFHTTPSessionManager *sessionMgr = [AFHTTPSessionManager manager];
    
    sessionMgr.responseSerializer.acceptableContentTypes = [[NSSet  alloc] initWithObjects:@"application/json", nil];
    //    sessionMgr.responseSerializer.acceptableContentTypes = [[NSSet  alloc] initWithObjects:@"text/html", nil];
    
    AFJSONResponseSerializer *json =[AFJSONResponseSerializer serializer];
    json.removesKeysWithNullValues = YES;
    sessionMgr.responseSerializer = json;
    
    sessionMgr.requestSerializer=[AFHTTPRequestSerializer serializer];
    
    // 设置超时时长
    [sessionMgr.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    sessionMgr.requestSerializer.timeoutInterval = 10.0;
    [sessionMgr.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    [sessionMgr POST:API_uploadImageUrl parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // hud
        [SVProgressHUD dismiss];
        NSLog(@"responseObject:%@", responseObject);
        
        NSInteger struts = [responseObject[@"fh"] integerValue];
        if (struts == 1){
            
            [SVProgressHUD showSuccessWithStatus:@"上传成功"];
//            [self loadUrlWith:API_upRefreshUrl];
        }else{
            
            [SVProgressHUD showErrorWithStatus:@"上传失败"];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"error:%@", error);
        [SVProgressHUD dismiss];
        if (error.code == -1009) {  // 网络连接错误
            
            [SVProgressHUD showErrorWithStatus:@"网络连接错误"];
        }else if (error.code == -1001){ // 链接超时
            
            [SVProgressHUD showErrorWithStatus:@"请求超时"];
        }else{
            
            [SVProgressHUD showErrorWithStatus:@"请求错误"];
        }
    }];
    
    [sessionMgr.operationQueue cancelAllOperations];
}


- (void)getTaobaoCertificationInfoWith:(NSString *)taskID
{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        //    hud.mode = MBProgressHUDModeText;
        hud.label.text = @"正在认证...";
    });
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        NSString *urlStr = [NSString stringWithFormat:@"https://api.shujumohe.com/octopus/sdk.service.task.query/v3?partner_code=%@&partner_key=%@", kPartner_code, kPartner_key];
        //    NSString *urlStr = @"https://api.shujumohe.com/octopus/sdk.service.task.query/v3";
        
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"task_id"] = taskID;
        param[@"partner_code"] = kPartner_code;
        param[@"partner_key"] = kPartner_key;
        
        
        AFHTTPSessionManager *sessionMgr = [AFHTTPSessionManager manager];
        sessionMgr.responseSerializer.acceptableContentTypes = [[NSSet  alloc] initWithObjects:@"application/json", nil];
        //    sessionMgr.responseSerializer.acceptableContentTypes = [[NSSet  alloc] initWithObjects:@"text/html", nil];
        
        AFJSONResponseSerializer *json =[AFJSONResponseSerializer serializer];
        json.removesKeysWithNullValues = YES;
        sessionMgr.responseSerializer = json;
        
        sessionMgr.requestSerializer=[AFHTTPRequestSerializer serializer];
        
        WeakSelf(weakSelf)
        // API_uploadImageUrl
        [sessionMgr POST:urlStr parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            // hud
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            NSLog(@"responseObject:%@", responseObject);
            
            NSInteger code = [responseObject[@"code"] integerValue];
            if (code == 0){
                
                weakSelf.taobaoCertificationDict = responseObject[@"data"];
                [weakSelf uploadTaobaoCertification];
                return;
            }else if (code == 100 || code == 2012){
                
                if (self.taobaoCertificationCount >= 3) {
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [SVProgressHUD showErrorWithStatus:@"认证处理中请稍后重试"];
                    });
                }else{
                    
                    self.taobaoCertificationCount++;
                    [weakSelf getTaobaoCertificationInfoWith:taskID];
                }
                return;
            }else{
                
                NSString *message = responseObject[@"message"];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showErrorWithStatus:message.length > 0 ? message : @"未知错误"];
                });
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            NSLog(@"error:%@", error);
            [SVProgressHUD dismiss];
            if (error.code == -1009) {  // 网络连接错误
                
                [SVProgressHUD showErrorWithStatus:@"网络连接错误"];
            }else if (error.code == -1001){ // 链接超时
                
                [SVProgressHUD showErrorWithStatus:@"请求超时"];
            }else{
                
                [SVProgressHUD showErrorWithStatus:@"请求错误"];
            }
        }];
    });
}


- (void)uploadTaobaoCertification
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"extra"] = @"{}";//self.taobaoCertificationDict;
    param[@"userid"] = @"73";
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //    hud.mode = MBProgressHUDModeText;
    hud.label.text = @"正在认证...";
    
    AFHTTPSessionManager *sessionMgr = [AFHTTPSessionManager manager];
    
    AFJSONResponseSerializer *json =[AFJSONResponseSerializer serializer];
    //    json.removesKeysWithNullValues = YES;
    sessionMgr.responseSerializer = json;
    sessionMgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
//    sessionMgr.responseSerializer.acceptableContentTypes = [[NSSet  alloc] initWithObjects:@"text/html", nil];
    
    sessionMgr.requestSerializer = [AFJSONRequestSerializer serializer];//[AFJSONRequestSerializer serializer]
    
    // 设置超时时长
//    [sessionMgr.requestSerializer willChangeValueForKey:@"timeoutInterval"];
//    sessionMgr.requestSerializer.timeoutInterval = 60.0;
//    [sessionMgr.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    WeakSelf(weakSelf)
    // API_uploadImageUrl self.tbJk self.tbJk @"https://www.51xintiao.cn/tbrzAz" https://www.51xintiao.cn/muser/myTbrz_ajax.action
    [sessionMgr POST:@"https://www.51xintiao.cn/muser/myTbrz_ajax.action" parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // hud
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSLog(@"responseObject:%@", responseObject);
        
//        NSData *strData = responseObject;
//        NSString *nameStr =  [[NSString alloc]initWithData:strData encoding:NSUTF8StringEncoding];
//        NSLog(@"responseObject2:%@", nameStr);
        
        NSInteger struts = [responseObject[@"fh"] integerValue];
        if (struts == 1){
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showSuccessWithStatus:@"保存成功"];
                [weakSelf loadUrlWith:weakSelf.tbrzfhUrl];
            });
        }else if(struts == 2){
            
            [SVProgressHUD showErrorWithStatus:@"您已经认证过了"];
        }else if(struts == 0){
            
            [SVProgressHUD showErrorWithStatus:@"参数为空"];
        }else{
            
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSLog(@"error:%@", error);
        [SVProgressHUD dismiss];
        if (error.code == -1009) {  // 网络连接错误
            
            [SVProgressHUD showErrorWithStatus:@"网络连接错误"];
        }else if (error.code == -1001){ // 链接超时
            
            [SVProgressHUD showErrorWithStatus:@"请求超时"];
        }else{
            
            [SVProgressHUD showErrorWithStatus:@"请求错误"];
        }
    }];
    
}


#pragma mark - action
- (void)onBtnClicked:(UIButton *)sender
{
    
    [self uploadTaobaoCertification];
    return;
    if (self.taskID.length > 0) {
        
        [self getTaobaoCertificationInfoWith:self.taskID];
    }else{
        
        [self taobaoCertification];
    }
    
//    NSString *alertJs=@"javascript:window.js.upLoadSfsb('101')";
//    [_jsContext evaluateScript:alertJs];
    
//    VRAuthenticationViewController *authVc = [[VRAuthenticationViewController alloc] init];
//    authVc.sfsbJk = self.sfsbJk;
//    [self presentViewController:authVc animated:NO completion:nil];
}

- (void)onBackBtnClick:(UIButton *)sender
{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }else{
        [self dismissViewControllerAnimated:NO completion:nil];
    }
}


- (void)onSaveAction
{
    
    VRAuthenticationViewController *authVc = [[VRAuthenticationViewController alloc] init];
    [self presentViewController:authVc animated:NO completion:nil];
}


#pragma mark - 处理cookie
//- (void)saveSessionIDCookie {
//    NSArray *nCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
//    NSHTTPCookie *cookie = nil;
//    for (id cObj in nCookies) {
//        if ([cObj isKindOfClass:[NSHTTPCookie class]]){
//            cookie = (NSHTTPCookie *)cObj;
//            if (!!cookie && [cookie.name isEqualToString:@"XTCookies"]) {
//                NSString *savePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
//                NSString *saveFile = [savePath stringByAppendingPathComponent:PHPSESSID];
//                [NSKeyedArchiver archiveRootObject:cookie toFile:saveFile];
//            }
//            NSLog(@"cookie properties: %@", cookie.properties);
//        }
//    }
//}
//
//- (void)restoreCookieIfNeeded {
//
//    NSString *savePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
//    NSString *saveFile = [savePath stringByAppendingPathComponent:PHPSESSID];
//    NSHTTPCookie *sessionIDCookie = [NSKeyedUnarchiver unarchiveObjectWithFile:saveFile];
//    if (!!sessionIDCookie) {
//        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:sessionIDCookie];
//    }
//}
- (void)saveCookie
{
    
    NSUserDefaults *userdef = [NSUserDefaults  standardUserDefaults];
    
    NSMutableArray *cookieArray = [NSMutableArray array];
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (int i = 0;  i < cookieJar.cookies.count; i ++) {

        NSHTTPCookie *cookie = [cookieJar cookies][i];
        if ([cookie.name isEqualToString:@"JSESSIONID"]) {

            [cookieArray addObject:cookie];
            NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject:cookieArray];
            [userdef setObject:cookiesData forKey:@"XTCookies"];
            
            [userdef synchronize];
        }
    }
    
    NSLog(@"-----------saveCookie:%@", cookieArray);
}


-(void)setCurcookies{
    
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in storage.cookies) {
        [storage deleteCookie:cookie];
    }
    
    NSUserDefaults *usedef = [NSUserDefaults standardUserDefaults];
    NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:[usedef objectForKey:@"XTCookies"]];
    NSLog(@"cookies:%@", cookies);
    for (NSHTTPCookie *cookie in cookies) {
        [storage setCookie:cookie];
    }
}


#pragma mark - UIWebViewDelegate
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    NSLog(@"----------webViewDidStartLoad----url:%@", webView.request.URL.absoluteString);
    [self createJSBridge];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSLog(@"----------webViewDidFinishLoad----url:%@", webView.request.URL.absoluteString);
    [self saveCookie];

    [self createJSBridge];
    
    NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    NSArray *titleArray = nil;
    if (title.length > 0) {
        titleArray = [title componentsSeparatedByString:@"-"];
        if (titleArray.count > 0) {
            self.titleLbl.text = [titleArray lastObject];
        }else{
            self.titleLbl.text = title;
        }
    }
}


- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    
    NSLog(@"----------shouldStartLoadWithRequest:%@", request.URL.absoluteString);
    
//    [self createJSBridge];
    return YES;
}


#pragma mark cllocation代理方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    
    CLLocation *loc = locations.lastObject;
    [VRUserInfo shareUserInfo].latitude = loc.coordinate.latitude;
    [VRUserInfo shareUserInfo].longitude = loc.coordinate.longitude;
    
    NSLog(@"locationManager:lat:%lf, lng:%lf", loc.coordinate.latitude, loc.coordinate.longitude);
    
    [self.clMgr stopUpdatingLocation];
}


- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    if (status == kCLAuthorizationStatusDenied || status == kCLAuthorizationStatusRestricted) {
        
        self.alertView = [[VRAlertView alloc] initWithTitle:@"提示" message:@"定位服务未开启，请进入系统［设置］> [隐私] > [位置]中打开开关" sureBtn:@"去设置" cancleBtn:nil];
        self.alertView.isHidenAlertBySure = NO;
        self.alertView.resultIndex = ^(NSInteger index){
            
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            
            if([[UIApplication sharedApplication] canOpenURL:url]) {
                
                NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
                [[UIApplication sharedApplication] openURL:url];
                
            }
        };
        [self.alertView showXLAlertView];
    }else if (status != kCLAuthorizationStatusNotDetermined){
        
        //        self.launchImgView.hidden = YES;
        [self requestContactPermission];
    }
}

#pragma mark actionSheet代理方法
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (0 == buttonIndex) {
        
        NSString *mediaType = AVMediaTypeVideo;
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        if(authStatus == ALAuthorizationStatusRestricted || authStatus == ALAuthorizationStatusDenied){
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"你已经取消了“领券”访问您的相机权限，若要继续操作请到手机“设置->隐私”设置开启" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alert show];
            return;
        }
        
        [self takePhotoFromCamera];
    }else if (1 == buttonIndex){
        
        ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
        if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied){
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"你已经取消了“领券”访问您的相册权限，若要继续操作请到手机“设置->隐私”设置开启" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alert show];
            return;
        }
        
        [self takePhotoFromPhotoLibrary];
    }
}


#pragma mark - VRAuthenticationViewControllerDelegate
- (void)authenticationSaveSuccessed
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self loadUrlWith:self.sfzfhUrl];
    });
}

#pragma mark - XScanViewControllerDelegate
- (void)getScanResultxxxxxxxxxxx:(NSString *)stringValue
{
    if (![stringValue hasPrefix:@"http"]) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"不是有效的地址，请重试" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alert animated:true completion:nil];
        return;
    }

    
    VRWebViewController *webVc = [[VRWebViewController alloc] init];
    webVc.isHaveNav = YES;
    webVc.urlStr = stringValue;
    [self presentViewController:webVc animated:NO completion:nil];
}


#pragma mark - tool
// 字典转json字符串方法

-(NSString *)convertToJsonData:(id)dict

{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0, jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}


#pragma mark - setter && getter
- (CLLocationManager *)clMgr
{
    if (nil == _clMgr) {
        _clMgr = [[CLLocationManager alloc] init];
        _clMgr.delegate = self;
        _clMgr.desiredAccuracy = kCLLocationAccuracyBest;
        //        _clMgr.allowsBackgroundLocationUpdates = YES;
        if ([_clMgr respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            NSLog(@"requestAlwaysAuthorization");
            [_clMgr requestAlwaysAuthorization];
        }
        
        //开始定位，不断调用其代理方法
        [_clMgr requestWhenInUseAuthorization];
    }
    return _clMgr;
}


- (NSString *)newUser_Agent{
    
    
    NSString *verson = [NSString stringWithFormat:@"%d_%d",[self getRandomNumber:7 to:10], [self getRandomNumber:1 to:3]];
    NSString *webKitVerson = [NSString stringWithFormat:@"%d",[self getRandomNumber:1 to:12]];
    
    NSString *useragent = [NSString stringWithFormat:@"Mozilla/5.0 (iPhone; CPU iPhone OS %@ like Mac OS X) AppleWebKit/602.3.%@ (KHTML, like Gecko) Mobile/14C89", verson, webKitVerson];
    
    // 项目名
    NSString *name =  [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleIdentifierKey];
    NSString *bundleVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleVersionKey];

    NSString *userAgent = [NSString stringWithFormat:@"%@;%@/%@ (%@; iOS %@; Scale/%0.2f) 123132afdfaddfadfdaffdafdafafdafadfa2ew1231231231dfdsafafdasfadsfadsfdasfasfdasfa3423423432fdgdasfaf23423rfrr43q4tefadgaea45qawdfafdaf1213sfaa32e2rewr3tewR34WR24RW24WS234DFA32434DF32R3432GAW3234G34332FA231421DFA2342AFER2342334R32FADFAS2432360123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199",useragent, name, bundleVersion, [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]];
    return userAgent;
}


- (int)getRandomNumber:(int)from to:(int)to
{
    return (int)(from + (arc4random() % (to - from + 1)));
}


@end
